<?php
namespace App\Console\Commands;

use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use swoole_websocket_server;

class WebSocketServerCommand extends Command
{
    public $ws;

    protected $userListCacheKey = 'socket_user_list';
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole {action}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'websocket 服务';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $arg = $this->argument('action');
        switch ($arg) {
            case 'start':
                $this->info('swoole server started');
                $this->start();
                break;
            case 'stop':
                $this->info('swoole server stoped');
                $this->stop();
                break;
            case 'restart':
                $this->info('swoole server restarted');
                $this->restart();
                break;
        }
    }

    /**
     * 启动Swoole.
     */
    private function start()
    {
        Redis::del($this->userListCacheKey);
        $this->ws = new swoole_websocket_server('0.0.0.0', config('websocket.port'));

        //监听WebSocket连接打开事件
        $this->ws->on('open', function ($ws, $request) {
            $userId = $request->fd;
            Redis::hset($this->userListCacheKey, $request->fd, $userId);
            $this->info("client $request->fd is connected\n");
            $this->pushMessage($request->fd, "welcome！client $request->fd connected！\n");
        });

        //监听WebSocket消息事件
        $this->ws->on('message', function ($ws, $frame) {
            $this->receiveMessageHandler($frame->fd, $frame->data);
        });

        //监听WebSocket主动推送消息事件
        $this->ws->on('request', function ($request, $response) {
            $this->messageHandler($request->post);
            Log::info(\GuzzleHttp\json_encode($request->post));
            $response->end('ok');
        });

        //监听WebSocket连接关闭事件
        $this->ws->on('close', function ($ws, $fd) {
            if (Redis::hexists($this->userListCacheKey, strval($fd))) {
                Redis::hdel($this->userListCacheKey, [strval($fd)]);
            }
            $this->info("client $fd is close\n");
        });
        $this->ws->start();
    }

    private function stop()
    {
        exec('ps -ef | grep \'swoole start\'', $result);

        if ($result) {
            foreach ($result as $item) {
                $process = explode(' ', preg_replace('#\s{2,}#', ' ', $item));
                if (isset($process[1])) {
                    $command = 'exec kill ' . $process[1];
                    $this->info($command);
                    exec($command);
                }
            }
        }

        $command = 'rm -rf ' . base_path('storage/framework/cache/*');
        $this->info($command);
        exec($command);
    }

    private function restart()
    {
        $this->stop();
        $this->start();
    }

    private function receiveMessageHandler($fd, $message)
    {
        if ($message === 'ping') {
            @$this->ws->push($fd, 'ping');
        } else {
            if (json_decode($message)) {
                $message = json_decode($message);
                if ($message->to > 0) {
                    $this->pushMessage($message->to, $message->msg, $fd);
                } else {
                    $this->info("receive client $fd message:" . $message->to);
                    $this->pushMessageToAll($message->msg);
                }

            } else {
                $this->pushMessageToAll($message);
            }
        }
    }

    private function messageHandler($data)
    {
        if (isset($data['type']) && in_array($data['type'], ['single', 'broadcast', 'group']) && isset($data['msg']) && $data['msg']) {
            if ('single' == $data['type'] && isset($data['fd']) && is_int((int)$data['fd']) && $data['fd'] > 0) {
                $this->pushMessage((int)$data['fd'], $data['msg']);
            }
            if ('broadcast' == $data['type']) {
                $this->pushMessageToAll($data['msg']);
            }
            if ('group' == $data['type'] && isset($data['groupId']) && $data['groupId']) {
                $fdList = Redis::HGETALL($this->userListCacheKey . "_" . $data['groupId']);
                if ($fdList) {
                    foreach ($fdList as $fd) {
                        $this->pushMessage($fd, $data['msg']);
                    }
                }
            }
        }

        $this->info("send to " . $data['type'] . " messages: " . $data['msg']);
    }

    private function pushMessageToAll($message)
    {
        $fdList = Redis::HGETALL($this->userListCacheKey);
        if ($fdList) {
            foreach ($fdList as $fd) {
                $this->info("send to " . $fd . " messages: " . $message);
                $this->pushMessage($fd, $message);
            }
        }

    }

    private function pushMessage($fd, $message, $from = 'sys', $type = 'broadcast')
    {
        $fd = (int)$fd;
        if ($this->ws->isEstablished($fd)) {
            @$this->ws->push($fd, json_encode([
                'type' => $type,
                'from' => $from,
                'msg' => $message,
            ]));
        }
    }

}
